package com.thuan.db;


import java.sql.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.thuan.pojo.UserAccount;

public class UserDAO implements IUserDAO{
	
	private static SessionFactory sessionFactory;	
	
	public static void setSessionFactory(SessionFactory sessionFactory) {
		UserDAO.sessionFactory = sessionFactory;
	}


	@Override
	public List<UserAccount> getUsers() {
		Session session = sessionFactory.openSession();

		List users = session.createQuery("from UserAccount").list();
		session.beginTransaction().commit();
		session.close();
		
		return users;
	}

	@Override
	public int addUser(String username, String password, String name) {
		if(findUser(username) != null)
			return -1;
		
		UserAccount userAccount = new UserAccount(username, password, name, 0, 0, 0, null);
		Session session = sessionFactory.openSession();
		session.save(userAccount);
		session.beginTransaction().commit();
		session.close();
		
		return 0;
	}

	@Override
	public UserAccount findUser(String username) {
		UserAccount result = null;
		
		Session session = sessionFactory.openSession();
		
		Query query = session.createQuery("from UserAccount where username = :username");
		query.setParameter("username", username);
		List users = query.list();
		
		if(!users.isEmpty())
			result = (UserAccount) users.get(0);
		
		session.close();
		return result;
	}


	@Override
	public boolean updateName(String username, String name) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public boolean updatePassword(String username, String password) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public boolean updateSigninTime(String username, Date signinTime) {
		// TODO Auto-generated method stub
		return false;
	}


	public boolean login(String username, String password) {
		boolean result = false;
		
		Session session = sessionFactory.openSession();
		
		Query query = session.createQuery("from UserAccount where username = :username and password = :password");
		query.setParameter("username", username);
		query.setParameter("password", password);
		List users = query.list();
		
		if(!users.isEmpty())
			result = true;
		
		session.close();
		return result;
	}
}

